import db, os
import sound
import serial
import time

class Machine(object):
    """
    The machine is responsible for playing sounds, sending data via serial port and check that the database is correct.
    """
    
    def __init__(self, table, port, parity = serial.PARITY_NONE, baudrate = 4800, bytesize = serial.EIGHTBITS, stopbits = serial.STOPBITS_ONE):
        """
        Check if the database exists, otherwise creates and adds the appropriate data.
        """
	
	# REVISAR PATH SI ES LLAMADO DESDE OTRO CWD
        path = os.getcwd()
        self.table = table
        self.port = port
	self.baudrate = baudrate
        self.error = False
        self.mic = False
        
        # creating the serial port connection
        self.serial = serial.Serial(port = self.port, parity = parity, baudrate = self.baudrate, bytesize = bytesize, stopbits = stopbits)

        # disable all channels
        self.serial.write("00")

        # creating or connecting with the database
        if not os.path.isfile(path + "data.db"):
            self.db = db.DB()
            try:
                f = open(table,"r")
                    
                while True:
                    line = f.readline()
                    
                    if not line: break
                    
                    parts = line.split(':')

                    #delete "\n" from the last element
                    parts[-1] = parts[-1][:-1]

                    self.db.add(parts)
                
                f.close()
            except IOError:
                self.error = True
                self.merror = "ERROR: El archivo " + self.table + " no existe."
                
        else:
            self.db = DB()

            
    def play_sound(self, key):
        """Sends the data through the serial port and plays the sound."""

        if key == "f": # DEFINIR TECLA DE MIC !
            if self.mic:
                self.serial.write("00")
                print "Mic desactivado"
                self.mic = False
            else:
                self.serial.write("ff")
                print "Mic activado"
                self.mic = True

            return None
            
        if not self.mic:

            #search data from key
            tuple = self.db.search(key)

            if tuple:
                # send via serial port
                self.serial.write(str(tuple[-2]))

                #play the sound
                sound.play(tuple[1])
                time.sleep(tuple[-1])
                print key + " --- Se reprodujo sonido"
                self.serial.write("00")
            else:
                print key + " --- Nada con esa letra"
    
    def __del__(self,):
        """Close serial port."""
        self.serial.close()


if __name__ == "__main__":
    life = Machine("data.txt", 0)

    if life.error:
        print life.merror

    life.play_sound("b") # or a

    if life.error:
        print life.merror
    
    life.db.cursor.execute('select * from data')

    # Veo todo lo que tiene la base de datos de una forma no recomendada..
    # deberia hacer un metodo para tal..
    for t in life.db.cursor:
        print t

    raw_input('Presione enter para terminar..')
